package com.bank.accountinfo.user.service.impl;

import com.bank.setting.standard.utils.JwtUtil;
import com.bank.accountinfo.user.dao.UserDao;
import com.bank.accountinfo.user.entity.User;
import com.bank.accountinfo.user.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private JwtUtil jwtUtil;


    @Override
    public User getUserById(Long id) {
        return userDao.selectById(id);
    }

    @Override
    @Transactional
    public boolean addUser(User user) {
        return userDao.insert(user) > 0;
    }

    @Override
    @Transactional
    public boolean updateUser(User user) {
        return userDao.updateById(user) > 0;
    }

    @Override
    @Transactional
    public boolean deleteUserById(Long id) {
        return userDao.deleteById(id) > 0;
    }

    @Override
    public List<User> getAllUsers() {
        return userDao.selectList(null);
    }

    @Override
    @Transactional
    public boolean batchInsert(List<User> userList) {
        return userDao.insertBatchSomeColumn(userList) > 0; // MyBatis-Plus提供了批量插入的方法
    }

    @Override
    public Page<User> getUserPage(Page<User> userPage) {
        return userDao.selectPage(userPage, null);
    }

    @Override
    public Map<String, Object> login(User user) {
        //根据用户名和密码查询
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(User::getName,user.getName());
        wrapper.eq(User::getPassword,user.getPassword());
        User loginUser=userDao.selectOne(wrapper);
        if (loginUser!=null){
            //String key="user:"+ UUID.randomUUID();//uuid
            loginUser.setPassword(null);
            String token =jwtUtil.createToken(loginUser);
            //返回数据
            Map<String,Object> data=new HashMap<>();
            data.put("token",token);
            return data;
        }
        //结果不为空，则生成token,并将用户信息存入redis
        return null;
    }

}
